package tr.muyat.server.bt;

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.nio.ByteBuffer;

import javax.microedition.io.StreamConnection;

public class ProcessConnectionThread extends Thread {

	private StreamConnection mConnection;

	// Constant that indicate command from devices
	private static final int EXIT_CMD = -1;
	private static final int KEY_RIGHT = 1;
	private static final int KEY_LEFT = 2;

	public ProcessConnectionThread(StreamConnection connection) {
		mConnection = connection;
	}

	@Override
	public void run() {
		try {
			// prepare to receive data
			InputStream inputStream = mConnection.openInputStream();

			System.out.println("waiting for input");
			byte[] buffer = new byte[256];
			
			while (true) {
				int command = inputStream.read(buffer);

				if (command == EXIT_CMD) {
					System.out.println("finish process");
					break;
				}
				// processCommand(command);
				processCommand(buffer, command);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void processCommand(byte[] buffer, int length) {
		
		ByteBuffer buf = ByteBuffer.wrap(buffer, 0, length);
		for (int i = 0; i < length / 4; i++) {
			float float1 = buf.getFloat();
			System.out.println("Number-" + i + ": " + float1);
		}
	
	}

	/**
	 * Process the command from client
	 * 
	 * @param command
	 *            the command code
	 */
	private void processCommand(int command) {
		try {
			Robot robot = new Robot();
			switch (command) {
			case KEY_RIGHT:
				robot.keyPress(KeyEvent.VK_RIGHT);
				System.out.println("Right");
				break;
			case KEY_LEFT:
				robot.keyPress(KeyEvent.VK_LEFT);
				System.out.println("Left");
				break;
			default:
				System.out.println("Unrecognized Command:" + command);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
